﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KPIS.GERP.Models.Class;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class FileController : Controller
    {
        //
        // GET: /File/
        private string[] _basicIncludeSubclass = new[]
		    {
				"SysProcess" 
		    };

        public ActionResult Index(int id, int type, string message = null, bool EmptyLayout = false) //Index(int id = 1, int type = 22)
        {
            ViewBag.Id = id;
            ViewBag.Type = type;
            var service = new FileService.FileServiceClient();
            ViewBag.Message = message;
            ViewBag.EmptyLayout = EmptyLayout;
            return View(service.Select(new KPIS.GERP.Models.ICM.File { RefId = id, RefType = type, RecordStatus = "!" + Models.SYS.RecordStatus.DeletedStatus }, null));
        }

        public ActionResult Create(int id, int type)
        {
            ViewBag.Id = id;
            ViewBag.Type = type;
            Models.ICM.File model = new Models.ICM.File();
            model.RefId = id;
            model.RefType = type;
            return View(model);
        }

        public bool FileType(String file_extentions)
        {
            bool ret = false;
            
                if(file_extentions.ToLower().StartsWith(".doc"))
                    ret = true;
                else if(file_extentions.ToLower().StartsWith(".txt"))
                    ret = true;
                else if(file_extentions.ToLower().StartsWith(".pdf"))
                    ret = true;
                else if(file_extentions.ToLower().StartsWith(".xls"))
                    ret = true;
                else if(file_extentions.ToLower().StartsWith(".ppt"))
                    ret = true;
                else if(file_extentions.ToLower().StartsWith(".jpg"))
                    ret = true;
                else if(file_extentions.ToLower().StartsWith(".png"))
                    ret = true;
                else if (file_extentions.ToLower().StartsWith(".gif"))
                    ret = true;
                else 
                    ret = false;          

            return ret;

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(KPIS.GERP.Models.ICM.File model, HttpPostedFileBase file, string FileNameHidden = null)
        {
            try
            {
                model.FileName = FileNameHidden;
                if (ModelState.IsValidField(model.FileName) && file.ContentLength > 0)
                {

                    ViewData["file_error"] = "";
                    //uploads file
                    if (file != null && file.ContentLength > 0)
                    {
                        string file_ext = Path.GetExtension(file.FileName);
                        if (!FileType(file_ext))
                        {
                            ViewData["file_error"] = "เอกสารแนบต้องเป็นเอกสารประเภท Word, Excel,PFD,Text,PowerPoint,JPEG,PNG หรือ GIF เท่านั้น!";
                            return View(model);
                        }
                        //string directory path
                        string folder_path = Server.MapPath("~/App_Data/uploads");

                        //check exists directory
                        DirectoryInfo di = new DirectoryInfo(folder_path);
                        if (!di.Exists)
                        {
                            System.IO.Directory.CreateDirectory(folder_path);
                            Models.Class.FileUtility.FolderACL("Everyone", folder_path);
                        }

                        //file.PostedFile.ContentType;
                        model.FileExtention = file_ext; // Path.GetExtension(file.FileName);
                        model.FileType = file.ContentType; //FileType(model.FileExtention);
                        // extract only the fielname
                        var fileName = Path.GetFileName(file.FileName);

                        model.FileName = fileName;
                        
                        fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + file_ext;

                        // store the file inside ~/App_Data/uploads folder
                        model.FilePath = Path.Combine(folder_path, fileName);

                        model.FileSizeByte = file.ContentLength;

                        file.SaveAs(model.FilePath);

                    }

                    var service = new FileService.FileServiceClient();

                    var id = service.Insert(model, Class.GimsMembership.CurrentEmpId);
                    
                    return RedirectToAction("Index", new {id = model.RefId, type = model.RefType});
                    //return RedirectToAction("Details", new { id });
                } else
                {
                    
                    ViewData["file_error"] = "ไม่สามารถเพิ่มเอกสารแนบได้:" + (model.FileName == null ? "ไม่ได้เลือกไฟล์":"") + (file.ContentLength == 0?"เป็นไฟล์ว่าง":"");
                    return View(model);
                }
            }
            catch (Exception ex)
            {
                ViewData["file_error"] = "ไม่สามารถเพิ่มเอกสารแนบได้:" + ex.Message;
                return View(model);
                //throw ex;
            }
            //return View(model);
        }

        public ActionResult Delete(int id, int refId, int refType)
        {
            try
            {
                var service = new FileService.FileServiceClient();
                service.Delete(id, Class.GimsMembership.CurrentEmpId);
                service.Close();
                return RedirectToAction("Index", new { id = refId, type = refType, message = "ลบข้อมูลแล้ว" });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public ActionResult Details(int id)
        {
            var service = new FileService.FileServiceClient();
            var model = service.Select(new KPIS.GERP.Models.ICM.File { FileId = id }, _basicIncludeSubclass).FirstOrDefault();
            return View(model);
        }

        public FileStreamResult StreamFileFromDisk4(int Id, bool dontCountAsLoaded = false)
        {
            var service = new FileService.FileServiceClient();
            var model = service.Select(new KPIS.GERP.Models.ICM.File { FileId = Id }, null).FirstOrDefault();
            string[] arr = model.FilePath.Split('\\');
            int len = arr.Length;
            string file = string.Empty;
            if (len > 1)
                file = arr[len - 1];
            string path = /*AppDomain.CurrentDomain.BaseDirectory +*/ Server.MapPath("~/App_Data/uploads/");
            if(!dontCountAsLoaded) service.AddCountLoadFileAsync(Id, Class.GimsMembership.CurrentEmpId);
            return File(new FileStream(path + file, FileMode.Open), model.FileType, model.FileName);
        }

        public FileStreamResult StreamFileFromDisk5(int Id)
        {
            var service = new FileService.FileServiceClient();
            var model = service.Select(new KPIS.GERP.Models.ICM.File { FileId = Id }, null).FirstOrDefault();
            string[] arr = model.FilePath.Split('\\');
            int len = arr.Length;
            string file = string.Empty;
            if (len > 1)
                file = arr[len - 1];
            string path = /*AppDomain.CurrentDomain.BaseDirectory +*/ Server.MapPath("~/../App_Data/uploads/");
            return File(new FileStream(path + file, FileMode.Open), model.FileType, file);
        }

        public FileStreamResult StreamFileFromDisk6(int Id)
        {
            var service = new FileService.FileServiceClient();
            var model = service.Select(new KPIS.GERP.Models.ICM.File { FileId = Id }, null).FirstOrDefault();
            string[] arr = model.FilePath.Split('\\');
            int len = arr.Length;
            string file = string.Empty;
            if (len > 1)
                file = arr[len - 1];
            string path = /*AppDomain.CurrentDomain.BaseDirectory +*/ Server.MapPath("~/../../App_Data/uploads/");
            return File(new FileStream(path + file, FileMode.Open), model.FileType, file);
        }


        public FileStreamResult StreamFileFromDisk7(int Id)
        {
            var service = new FileService.FileServiceClient();
            var model = service.Select(new KPIS.GERP.Models.ICM.File { FileId = Id }, null).FirstOrDefault();
            string[] arr = model.FilePath.Split('\\');
            int len = arr.Length;
            string file = string.Empty;
            if (len > 1)
                file = arr[len - 1];
            string path = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/uploads/";
            return File(new FileStream(path + file, FileMode.Open), model.FileType, file);
        }

        public FileStreamResult StreamFileFromDisk8(int Id)
        {
            var service = new FileService.FileServiceClient();
            var model = service.Select(new KPIS.GERP.Models.ICM.File { FileId = Id }, null).FirstOrDefault();
            string[] arr = model.FilePath.Split('\\');
            int len = arr.Length;
            string file = string.Empty;
            if (len > 1)
                file = arr[len - 1];
            string path = AppDomain.CurrentDomain.BaseDirectory + "../App_Data/uploads/";
            return File(new FileStream(path + file, FileMode.Open), model.FileType, file);
        }

        public FileStreamResult StreamFileFromDisk9(int Id)
        {
            var service = new FileService.FileServiceClient();
            var model = service.Select(new KPIS.GERP.Models.ICM.File { FileId = Id }, null).FirstOrDefault();
            string[] arr = model.FilePath.Split('\\');
            int len = arr.Length;
            string file = string.Empty;
            if (len > 1)
                file = arr[len - 1];
            string path = AppDomain.CurrentDomain.BaseDirectory + "../../App_Data/uploads/";
            return File(new FileStream(path + file, FileMode.Open), model.FileType, file);
        }

        public FilePathResult GetFileFromDisk1(int Id)
        {
            var service = new FileService.FileServiceClient();
            var model = service.Select(new KPIS.GERP.Models.ICM.File { FileId = Id }, null).FirstOrDefault();
           // return View(model);
            string[] arr = model.FilePath.Split('\\');
            int len = arr.Length;
            string file = string.Empty;
            if(len > 1)
                file = arr[len - 1];
           
            string path = /*AppDomain.CurrentDomain.BaseDirectory +*/ Server.MapPath("~/App_Data/uploads/");
            //string fileName = model.FileName+model.FileExtention;
            return File(path + file, model.FileType, file);
        }

        public FilePathResult GetFileFromDisk2(int Id)
        {
            var service = new FileService.FileServiceClient();
            var model = service.Select(new KPIS.GERP.Models.ICM.File { FileId = Id }, null).FirstOrDefault();
            // return View(model);
            string[] arr = model.FilePath.Split('\\');
            int len = arr.Length;
            string file = string.Empty;
            if (len > 1)
                file = arr[len - 1];

            string path = /*AppDomain.CurrentDomain.BaseDirectory +*/ Server.MapPath("../../App_Data/uploads/");
            return File(path + file, model.FileType, file);
        }

        public FilePathResult GetFileFromDisk3(int Id)
        {
            var service = new FileService.FileServiceClient();
            var model = service.Select(new KPIS.GERP.Models.ICM.File { FileId = Id }, null).FirstOrDefault();
            // return View(model);
            string[] arr = model.FilePath.Split('\\');
            int len = arr.Length;
            string file = string.Empty;
            if (len > 1)
                file = arr[len - 1];

            string path = /*AppDomain.CurrentDomain.BaseDirectory +*/ Server.MapPath("../../../App_Data/uploads/");
            return File(path + file, model.FileType, file);
        }

        public ActionResult ImagesByName(string imageName)
        {
            if (!string.IsNullOrWhiteSpace(imageName) && System.IO.File.Exists(GetImagePathByFileName(imageName)))
                return File(GetImagePathByFileName(imageName), FileUtility.GetMimeType(imageName));
            else
                return File(NoImageFilePath, "image/jpeg");
        }

        public ActionResult Images(int id)
        {
            if (System.IO.File.Exists(GetImagePathById(id)))
                return File(GetImagePathById(id), "image/jpeg");
            else
                return File(NoImageFilePath, "image/jpeg");
        }

        public ActionResult ImagesWithWater(int id)
        {
            string fileWatermark = Server.MapPath("~/Content/Images/Icon/logo.png");
            if (System.IO.File.Exists(GetImagePathById(id)))
            {
                return File(Watermark(GetImagePathById(id), fileWatermark), "image/jpeg");
            }

            return File(NoImageFilePath, "image/jpeg");
        }

        private byte[] Watermark(string file1, string filewater)
        {
            using (Image img = Image.FromFile(file1))
            using (Image wt = Image.FromFile(filewater))
            using (Graphics g = Graphics.FromImage(img))
            using (Brush b = new TextureBrush(wt))
            {
                int h = img.Size.Height;
                int w = img.Size.Width;
                int x = 25;
                int y = h - 45;
                int hLogo = 150;
                int wLogo = 70;
                var b3 = new TextureBrush(wt);

                var b2 = new SolidBrush(Color.FromArgb(70, 0, 0, 0));

                g.RotateTransform(-15);

                g.FillRectangle(b, x, y, hLogo, wLogo);
                g.DrawRectangle(Pens.Indigo, x, y, hLogo, wLogo);
                g.DrawString("Mars 1", new Font("tahoma", 40, GraphicsUnit.Point), b2, new PointF(x, y));

                g.RotateTransform(60);
                int x2 = 45;
                int y2 = h - 65;
                int hLogo2 = 150;
                int wLogo2 = 70;

                g.FillRectangle(b3, x2, y2, hLogo2, wLogo2);
                g.DrawRectangle(Pens.Indigo, x2, y2, hLogo2, wLogo2);
                g.DrawString("Mars 2", new Font("tahoma", 40, GraphicsUnit.Point), b3, new PointF(x2, y2));

                var ms = new MemoryStream();
                img.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }

        private string GetImagePathByFileName(string fileName)
        {
            var path = DirectoryImage + fileName;
            return FileUtility.IsItVirtualpath(Class.GimsConfigReader.GimsFileFolder) ? path : Server.MapPath(path);
        }

        private string GetImagePathById(int imageId)
        {
            var path = DirectoryImage + imageId + ".jpg";
            return FileUtility.IsItVirtualpath(Class.GimsConfigReader.GimsFileFolder) ? path : Server.MapPath(path);
        }

        private string NoImageFilePath
        {
            get { return Server.MapPath("~/Content/Images/Icon/no_image.png"); }
        }

        private string DirectoryImage
        {
            get
            {
                if (!FileUtility.IsItVirtualpath(Class.GimsConfigReader.GimsFileFolder))
                    return FileUtility.SingleSlashAtEndString(Class.GimsConfigReader.GimsFileFolder);

                return Class.GimsConfigReader.GimsFileFolder;

            }
        }
    }
}
